/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.uhk.ppro.response.web;

import cz.uhk.ppro.response.model.Course;
import cz.uhk.ppro.response.model.Teacher;
import cz.uhk.ppro.response.service.DatabaseService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 *
 * @author Martin Zmítko <martin.zmitko@gmail.com>
 */

@Controller
@RequestMapping("course.do")
public class CourseFormController {

    @Autowired
    private DatabaseService databaseSession;

    @RequestMapping(method=RequestMethod.POST)
    public String onSubmit(
            @RequestParam(value="id",required=false) Integer id,
            @ModelAttribute("course") Course command)
    {
        if (id != null) {
            databaseSession.upravKurz(command);
            return "redirect:/course.do?id=" + id;
        } else {
            databaseSession.pridejKurz(command);
            return "redirect:/courses.do";
        }
    }

    @ModelAttribute("teachers")
    public List<Teacher> populateTeachers() {
        return databaseSession.getTeachers();
    }

    @RequestMapping(method=RequestMethod.GET)
    protected String setupForm(@RequestParam(value="id",required=false) Integer id, Model m)
    {
        Course c;
        if (id!=null) {
            c = databaseSession.getCourseById(id);
            m.addAttribute("joinedTest", databaseSession.getTestsConnectedByCourse(c));
            m.addAttribute("joinedStudent", databaseSession.getStudentsConnectedByCourse(c));
        } else {
            c = new Course();
        }

        c.setTeacher(databaseSession.getLoggedTeacher());

        if (id!=null) {
            m.addAttribute("course", c);
        } else {
            m.addAttribute("course", c);
        }
        
        return "formCourse";
    }

    /**
     * puvodni nacteni ucitele
     * <form:select path="teacher.id" id="inputTeacher" >
     *     <form:option value=""><spring:message code="form.choose" /></form:option>
     *     <c:forEach var="r" items="${teachers}">
     *         <form:option value="${r.id}">${r.firstName} ${r.lastName}</form:option>
     *     </c:forEach>
     * </form:select>
     */

}
